package bean;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class boardDTO {
	private boardVO vo = null;
	private Connection conn = null;
	
	int listSize = 3;	// 페이지당 표시되는 행수  
	int blockSize = 3;	// 한 블럭당 표시되는 페이지수 
	int totSize = 0;	// 전체 게시물의 갯수
	int totPage = 0;	// 현재 페이지  
	int totBlock = 0; 	// 전체 블럭수
	int nowPage = 1;	// 현재 페이지 
	int nowBlock = 1;	// 현재 블럭
	int startNo = 0; 	// 리스트 목록의 시작 위치 
	int endNo = 0; 		// 리스트 목록의 끝 위치 
	int startPage = 0; 	// 현재 블럭에서 표시되는 시작 블럭번호
	int endPage = 0;	// 현재 블럭에서 표시되는 끝 블럭 번호 	
	
	String saveDir="C:/Users/user/Documents/workspace/Web/WebContent/04JSP/01MemberPhoto/";
	
		public boardDTO() {
		conn = new MyOracle().getConn();
	}	
	
	public boolean insert(){ 			//입력 메소드 
		boolean b = false;
		String sql = "insert into board01(m_id, b_pw, b_date, b_modifyDate, b_title, b_content, b_number, b_image) "
				+ " values(?,?,sysdate,sysdate,?,?,seq_board01.nextval,?)";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getM_id());
			pst.setString(2, vo.getB_pw());
			pst.setString(3, vo.getB_title());
			pst.setString(4, vo.getB_content());
			pst.setString(5, vo.getB_image());
		
			int cnt = pst.executeUpdate();
			if (cnt>0) b=true;
			
			pst.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	 
	}
	
	public ArrayList<boardVO> select(){	// list - 검색과 리스트 처리 
		ArrayList<boardVO> al = new ArrayList<boardVO>();
		String sql = "select * from ("
				+ " select rownum rn, c.*from("
				+ " select * from board01 "
				+ " where m_id like ? or b_title like ? or b_content like ? order by b_number desc)c"
				+ " )b"
				+ " where b.rn between ? and ? ";
		try{
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%" + vo.getFind() + "%");
			pst.setString(2, "%" + vo.getFind() + "%");
			pst.setString(3, "%" + vo.getFind() + "%");
			pst.setInt(4, startNo);
			pst.setInt(5, endNo);
			
			ResultSet rs = pst.executeQuery();
			while(rs.next()){
				boardVO v = new boardVO();
				v.setB_number(rs.getInt("b_number"));
				v.setB_title(rs.getString("b_title"));
				v.setB_date(rs.getString("b_date"));
				v.setM_id(rs.getString("m_id"));
				v.setB_image(rs.getString("b_image"));
				al.add(v);
			}
			rs.close();
			pst.close();
			conn.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return al; 
	}
	
	public void page(){					// list - page 처리 
    	String sql = "select count(*) cnt from board01 where m_id like ? or b_title like ?";
    	try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%"+vo.getFind()+"%");
			pst.setString(2, "%"+vo.getFind()+"%");
			ResultSet rs = pst.executeQuery();
			if(rs.next()){
			totSize = rs.getInt("cnt"); 
			// 전체 페이지수 
			totPage = (int)Math.ceil(totSize*1.0/listSize);
			// 전체 블럭수
			totBlock = (int)Math.ceil(totPage*1.0/blockSize);
			// 현재블럭
			nowBlock = (int)Math.ceil(nowPage*1.0 / blockSize);
			// 페이지의 시작과 끝 번호 
			endPage = nowBlock * blockSize;
			startPage = endPage-blockSize+1;
			// 게시물의 시작번호와 끝 번호
			endNo = nowPage * listSize;
			startNo = endNo-listSize + 1;
			// endPage, endNo 보정값
			if(endPage > totPage) endPage = totPage;
			if(endNo>totSize) endNo = totSize;
			}
			System.out.println("<li>totSize=" + totSize);
			System.out.println("<li>totPage=" + totPage);
			
			rs.close();
			pst.close();
			
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	}
	public boardVO view(){					// view 메소드  
		boardVO vo = new boardVO();
		String sql = "select * from board01 where b_number=?";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			System.out.println(vo.getB_number());
			pst.setInt(1, vo.getB_number());
			ResultSet rs = pst.executeQuery();
			while(rs.next()){
				vo.setB_number(rs.getInt("b_number"));
				vo.setB_title(rs.getString("b_title"));
				vo.setM_id(rs.getString("m_id"));
				vo.setB_date(rs.getString("b_date"));
				vo.setB_modifyDate(rs.getString("b_modifyDate"));
				vo.setB_content(rs.getString("b_content"));
				vo.setB_image(rs.getString("b_image"));
			}
			rs.close();
			pst.close();
			conn.close();
		} catch (Exception e) {

		}
		return vo;
	}
	public boolean delete(){			// 삭제 메소드 
		boolean b = false;
		String sql = "delete from board01 where b_number=?";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setInt(1, vo.getB_number());
			int cnt = pst.executeUpdate();
			System.out.println(vo.getB_image());
			if(cnt>0) b=true;
				String saveDir="C:/Users/user/Documents/workspace/Web/WebContent/04JSP/01MemberPhoto/";
				File f = new File(saveDir + vo.getB_image());
				if(f.exists()) f.delete();
			pst.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return b;
	}
	public boolean modify(){
		boolean b = false;
		String sql = "update board01 set m_id=?, b_pw=?, b_modifyDate=sysdate, b_title=?, b_content=?, b_image=? where b_number = ?";
		try {
			PreparedStatement pst =conn.prepareStatement(sql);
			pst.setString(1, vo.getM_id());
			pst.setString(2, vo.getB_pw());
			pst.setString(3, vo.getB_title());
			pst.setString(4, vo.getB_content());
			pst.setString(5, vo.getB_image());
			pst.setInt(6, vo.getB_number());
			int cnt = pst.executeUpdate();
			if (cnt>0) b=true;
			
			pst.close();
			conn.close();
				
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	
	public void ImageUpload(boardVO vo){
		this.vo = vo;
		int size =1024*1024*10; /* 파일사이즈 */
		
		String oriFile="";
		String sysFile=""; 
		MultipartRequest multi = null;
		try{
			multi = new MultipartRequest(vo.getRequest(), saveDir, size, "utf-8", new DefaultFileRenamePolicy());
			
			Enumeration files = multi.getFileNames();
			String tempFile = (String)files.nextElement();

			oriFile = multi.getOriginalFileName(tempFile);
			sysFile = multi.getFilesystemName(tempFile);
			
			vo.setM_id(multi.getParameter("m_id"));						//데이터 베이스에 저장
			vo.setB_pw(multi.getParameter("b_pw"));
			vo.setB_title(multi.getParameter("b_title"));
			vo.setB_content(multi.getParameter("b_content"));
			vo.setB_number(Integer.parseInt(multi.getParameter("b_number")));	// request는 String값만 받으므로, 숫자로 변환해준다. 
			if(sysFile == null || sysFile.equals("")){ 					// 수정시, 파일을 변경하지 않으면 원래 이미지가 나오게 한다. 
				vo.setB_image(multi.getParameter("b_oriImage"));
			}
			else{
				vo.setB_image(sysFile);									// 처음에 입력하거나, 수정시, 새 이미지가 나오게 한다. 
				// 섬네일 파일 추가 생성 (썸네일 안나올거면 안주면 됨) 
				ParameterBlock pd = new ParameterBlock();
				pd.add(saveDir + sysFile);
				RenderedOp rOp = JAI.create("fileload", pd);
				BufferedImage bi = rOp.getAsBufferedImage();
				BufferedImage thumb = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
				Graphics2D g = thumb.createGraphics();
				g.drawImage(bi, 0, 0, 100, 100, null);
				
				File file = new File(saveDir + "sm_" + sysFile);
				ImageIO.write(thumb,"png", file);
			}
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public boardVO getVo() {
		return vo;
	}

	public void setVo(boardVO vo) {
		this.vo = vo;
		this.nowPage = vo.getNowPage();
		this.nowBlock = vo.getNowBlock();
	}

	public Connection getConn() {
		return conn;
	}

	public void setConn(Connection conn) {
		this.conn = conn;
	}

	public int getListSize() {
		return listSize;
	}

	public void setListSize(int listSize) {
		this.listSize = listSize;
	}

	public int getBlockSize() {
		return blockSize;
	}

	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}

	public int getTotSize() {
		return totSize;
	}

	public void setTotSize(int totSize) {
		this.totSize = totSize;
	}

	public int getTotPage() {
		return totPage;
	}

	public void setTotPage(int totPage) {
		this.totPage = totPage;
	}

	public int getTotBlock() {
		return totBlock;
	}

	public void setTotBlock(int totBlock) {
		this.totBlock = totBlock;
	}

	public int getNowPage() {
		return nowPage;
	}

	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}

	public int getNowBlock() {
		return nowBlock;
	}

	public void setNowBlock(int nowBlock) {
		this.nowBlock = nowBlock;
	}

	public int getStartNo() {
		return startNo;
	}

	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}

	public int getEndNo() {
		return endNo;
	}

	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}

	public int getStartPage() {
		return startPage;
	}

	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}

	public int getEndPage() {
		return endPage;
	}

	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}
	
	
	
}
